#include "hex_line_edit.h"
#include <QMessageBox>
HexLineEdit::HexLineEdit(QWidget *parent) :
	QLineEdit(parent)
{
}

QByteArray &HexLineEdit::hexText(bool *ok)
{
    QByteArray textByteArray = this->text().toLatin1();
	const char *str = textByteArray.data();
	unsigned char ch, hData, lData;

	*ok = false;
	hexTextArray.clear();
	while((ch=*str++) != '\0')
	{
		if(ch>='0' && ch<='9')
		{
			hData = ch - '0';
		}
		else if(ch>='A' && ch<='F')
		{
			hData = ch-'A' + 10;
		}
		else if(ch>='a' && ch<='f')
		{
			hData = ch-'a' + 10;
		}
		else if(ch == ' ')
		{
			continue;
		}
		else
		{
			hexTextArray.clear();
			QMessageBox::critical(this, tr("Error Hex Format Data"), tr("Hex Data Error\n"
								  "Please input like: 31 32 33 34"));
			return hexTextArray;
		}
		ch = *str++;
		if(ch>='0' && ch<='9')
		{
			lData = ch - '0';
		}
		else if(ch>='A' && ch<='F')
		{
			lData = ch-'A' + 10;
		}
		else if(ch>='a' && ch<='f')
		{
			lData = ch-'a' + 10;
		}
		else if(ch == ' ')
		{
			hexTextArray.append(hData);
			continue;
		}
		else
		{
			if(ch == '\0')
			{
				hexTextArray.append(hData);
			}
			else
			{
				QMessageBox::critical(this, tr("Error Hex Format Data"), tr("Hex Data Error\n"
									  "Please input like: 31 32 33 34"));
				return hexTextArray;
			}
			break;
		}
		hexTextArray.append((hData<<4) + lData);
		ch = *str++;
		if(ch != ' ')
		{
			if(ch != '\0')
			{
				QMessageBox::critical(this, tr("Error Hex Format Data"), tr("Hex Data Error\n"
									  "Please input like: 31 32 33 34"));
				return hexTextArray;
			}
			break;
		}
	}
	*ok = true;
	return hexTextArray;
}
